<template>
  <div>
    <dialog-with-save
      :visible.sync="visible"
      :title="title"
      :width="width"
      @save="save"
    >
      <el-form
        ref="editForm"
        label-position="top"
        :model="model"
        :rules="rules"
      >
        <el-form-item
          :label="L('DisplayName')"
          prop="displayName"
        >
          <el-input
            v-model="model.displayName"
            autofocus
            type="text"
            :maxlength="32"
          />
        </el-form-item>
      </el-form>
    </dialog-with-save>
  </div>
</template>

<script>
import dialogWithSave from '@/components/DialogWithSave' // waves directive
import { mapActions } from 'vuex'
export default {
  name: 'CreateOrEditOu',
  components: { dialogWithSave },
  data() {
    return {
      title: '新建组织机构',
      visible: false,
      width: '500px',
      model: {
        parentId: null,
        id: '',
        displayName: ''
      },
      rules: {
        displayName: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('DisplayName')), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions('organizationUnit', ['createOrganizationUnit', 'updateOrganizationUnit']),
    open({ mode, title, model }) {
      this.visible = true
      this.$nextTick(() => {
        var map = { 'add-root': '新建组织机构', 'add-sub': '新建组织机构', 'edit': `修改: ${model.displayName}` }
        this.title = map[mode]
        this.model = model
        this.$refs.editForm.clearValidate()
      })
    },
    save(cb) {
      cb(() => {
        return new Promise((resolve, reject) => {
          this.$refs.editForm.validate(async val => {
            if (val) {
              if (this.model.id) {
                await this.updateOrganizationUnit(this.model).catch(err => { reject(err) })
              } else {
                await this.createOrganizationUnit(this.model).catch(err => { reject(err) })
              }
              this.$emit('loadOrganization')
              resolve(val)
            } else {
              reject(val)
            }
          })
        })
      })
    }
  }
}
</script>

